<?php
namespace Shopmodule\Model;
use Think\Model;
class LotteryModel {
	public $gifts;
	public $eid=0;
	public $sid;
	public $score_id;
	public $usernick;
	public $UserUZID; //全站用户名
	public $UserSPID; //店铺用户名
	public $readoid; //强制读取订单
	
	// 取活动参数
	// 取奖品
	// 取用户参与记录
	public function ShopLott(){
		$score_add = 0;
		$Shop = M("ShopCfg");
		$shopcfg = current($Shop->where("`sid`=".$this->sid)
					 ->getField("id,curtool,usernick,taobao_user_id,
								tms_newcomer,range_time,sumpay,trads,
								lotts,wins,start_time,end_time,
								range_time,withdraw,brandid,orderset,
								game_lv1_times,game_lv2_times,game_lv3_times,game_def_times,
								goodrate_times,order_payment,order_payment_addon,order_pay_time_start,
								order_pay_time_end,cart_items,order_items,order_success_times,
								order_pay_times,tms_newcomer,tms_cartadd,tms_goodrate,
								tms_everyday,collect,likeme,shareme,
								followme,sessionkey,goodrate_kwd,andor"
								));
		if(strtotime($shopcfg["end_time"])-time()<0){
			$reda["status"]=false;
			$reda["score"]=0;
			$reda["giftname"]="活动已经结束！";	
			return $reda;
		}
		if(strtotime($shopcfg["start_time"])-time()>0){
			$reda["status"]=false;
			$reda["score"]=0;
			$reda["giftname"]="活动尚未开始！";	
			return $reda;
		}
		// if(1==2&&($shopcfg["trads"]||$shopcfg["goodrates"]||$shopcfg["sumpay"])){
		// // 此处判断已下线，不再提供类似功能
		// $SHOPUSER = M("ShopUsers");
		// $udata = current($SHOPUSER->where("`id`=".$this->UserSPID)->getField("`id`,`rate_good`,`rate_neutral`,`rate_bad`,`trads`,`sumpay`"));

			// if($shopcfg["goodrates"]>0){
				// if($udata["rate_neutral"]>0||$udata["rate_bad"]>0){
				// // 仅好评用户可抽奖
				// $reda["status"]=false;
				// $reda["score"]=0;
				// $reda["giftname"]="您在历史交易中曾经给过我们中评或者差评，抱歉，您不能抽奖。";	
				// return $reda;
				// }
			// }else{
				// if($udata["rate_bad"]>0){
				// // 不允许差评用户抽奖
				// $reda["status"]=false;
				// $reda["score"]=0;
				// $reda["giftname"]="您在历史交易中曾经给过我们差评，抱歉，您不能抽奖。";	
				// return $reda;
				// }
			// }
			// if($shopcfg["sumpay"]>0&&$shopcfg["sumpay"]>$udata["sumpay"]){
				// // 仅累计消费达标用户可抽奖
				// $reda["status"]=false;
				// $reda["score"]=0;
				// $reda["giftname"]="抱歉，您在本店的消费额只有".$udata["sumpay"]."元，要消费".$shopcfg["sumpay"]."元以上才能抽奖哦！";	
				// return $reda;
			// }
			// if($shopcfg["trads"]>0&&$shopcfg["trads"]>$udata["trads"]){
				// // 仅交易次数达标用户可抽奖
				// $reda["status"]=false;
				// $reda["score"]=0;
				// $reda["giftname"]="抱歉，您在本店购买的次数只有".$udata["trads"]."次，要购买".$shopcfg["trads"]."次才可以抽奖哦！";	
				// return $reda;
			// }
		// }
		if($this->score_id){
		$Score = M("GameScore");
		$score_add += $Score->where("`id`=".$this->score_id." AND `status`=1")->getField("lotts");
		$ssav["status"]=2;
		$ssav["shopuid"]=$this->UserSPID;
		$Score->where("`id`=".$this->score_id)->save($ssav);
		}
		
		// if($this->oid&&($shopcfg["order_payment"]||$shopcfg["order_success_times"]||$shopcfg["order_pay_times"])){
		if($this->oid&&$shopcfg["orderset"]==1){
			$Order = M("Orders");
			// $where = $shopcfg["order_payment"]?" AND `payment`>".$shopcfg["order_payment"]:"";
			// $topics = $Order->where("`oid`=".$this->oid." AND `buyer_nick`='".$this->usernick."'")->getField("id,topic,status,payment");
			$topic = current($Order->where("`oid`=".$this->oid)->getField("id,topic,status,payment,buyer_nick"));//echo $Order->_sql();
			// if(!$topics){
				// $reda["status"]=false;
				// $reda["score"]=0;
				// $reda["giftname"]="抱歉，".($shopcfg["order_payment"]?$shopcfg["order_payment"]."元以上的订单才可以抽奖。":"")."该订单号已经使用过。";
				// return $reda;
			// }
			
			// var_dump($this->readoid);
			if($topic){
				$save = true;
			}
			if($topic&&!$this->readoid){
				// 已保存订单号逻辑
				if($shopcfg["order_payment"]>0){
					$bei = (int)($topic["payment"]/$shopcfg["order_payment"]);
					$bei = $shopcfg["order_payment_addon"]>$bei?$bei:$shopcfg["order_payment_addon"];
					// 超额倍数
				}
				if($topic["buyer_nick"]!=$this->usernick){
					$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="抱歉，该订单号不是你的哦！请换一个吧！";
					return $reda;
				}
				if($topic["status"]==4){
					$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="这个订单的所有机会都用完了。";
					return $reda;
				}
				if($topic["payment"]<$shopcfg["order_payment"]){
					$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="抱歉，".$shopcfg["order_payment"]."元以上的订单才可以抽奖。";
					if($shopcfg["andor"]!=1){
						return $reda;
					}
				}
				if($topic["status"]==2&&($topic["topic"]=="WAIT_SELLER_SEND_GOODS"||$topic["topic"]=="SELLER_CONSIGNED_PART"||$topic["topic"]=="WAIT_BUYER_CONFIRM_GOODS")){
					$reda["giftname"]="抱歉，该订单号已经抽过奖了。";
					if($shopcfg["order_success_times"]>0||$shopcfg["tms_goodrate"]>0){
						$reda["giftname"]="抱歉，该订单号付款时已经抽过奖了。";
					}
					if($shopcfg["order_success_times"]>0){
						$reda["giftname"].= "订单确认收货后可以抽".($bei>0?$shopcfg["order_success_times"]*$bei:$shopcfg["order_success_times"])."次";
					}
					if($shopcfg["tms_goodrate"]>0){
						$reda["giftname"].= "，而且好评后可以再抽".($bei>0?$shopcfg["tms_goodrate"]*$bei:$shopcfg["tms_goodrate"])."次";
					}
					$reda["giftname"].="哦，亲！";
					if($shopcfg["order_success_times"]>0||$shopcfg["tms_goodrate"]>0){
						$reda["giftname"].="<input class=\"btn btn-mini btn-warning js-dolott-ready\" data-oid=\"".$this->oid."\" value=\"已经收货/好评\" type\"button\">";
					}
					$reda["status"]=false;
					$reda["score"]=0;
					return $reda;
				}
				if($topic["status"]==3&&$topic["topic"]=="TRADE_FINISHED"){
					$reda["giftname"]="抱歉，该订单号";
					if($shopcfg["order_pay_times"]>0){
						$reda["giftname"]="抱歉，该订单号付款时已经抽过奖了。";
					}
					if($shopcfg["order_success_times"]>0){
						$reda["giftname"]="抱歉，该订单号确认收货时已经抽过奖了。";
					}
					if($shopcfg["tms_goodrate"]>0){
						$reda["giftname"].="好评时还未抽奖，";
						$reda["giftname"].= "订单好评后可以再抽".($bei>0?$shopcfg["tms_goodrate"]*$bei:$shopcfg["tms_goodrate"])."次哦，亲！";
						$reda["giftname"].="<input class=\"btn btn-mini btn-warning js-dolott-ready\" data-oid=\"".$this->oid."\" value=\"已经收货/好评\" type\"button\">";
					}
					$reda["status"]=false;
					$reda["score"]=0;
					return $reda;
				}
				if($topic["status"]==4&&$topic["topic"]=="TRADE_FINISHED"){
					$reda["giftname"].="抱歉，该订单号好评时已经抽过奖了。";
					$reda["status"]=false;
					$reda["score"]=0;
					return $reda;
				}
			}
			// 以上都不成立，进入读取订单数据环节
			if($this->readoid||$this->oid){
				Vendor('taobaosdk.top.TopClient');
				Vendor('taobaosdk.lotusphp_runtime.Logger.Logger');
				Vendor('taobaosdk.top.RequestCheckUtil');
				Vendor('taobaosdk.top.request.TradeGetRequest');
				$this->c =  new \TopClient();
				$this->c->appkey=C("SM_KEY");
				$this->c->secretKey=C("SM_SECRET");
				$this->c->format="xml";
				$req = new \TradeGetRequest;
				$req->setFields("buyer_nick,payment,orders.num_iid,price,num,buyer_rate,status,pay_time,end_time");
				$req->setTid($this->oid);
				$resp = $this->c->execute($req, $shopcfg["sessionkey"]);
				// print_r($resp);
				if($resp->code){
					$reda["status"]=false;
					$reda["score"]="0";
					if($resp->sub_msg){
						$reda["giftname"]="错误！".$resp->sub_msg;
					}else{
						$reda["giftname"]="错误！请输入正确的订单号！";
					}
					return $reda;
				}
				
				if($shopcfg["order_payment"]>0){
					$bei = (int)($resp->trade->payment/$shopcfg["order_payment"]);
					$bei = $shopcfg["order_payment_addon"]>$bei?$bei:$shopcfg["order_payment_addon"];
					// 超额倍数
				}
				if($resp->trade->status){
					if((string)$resp->trade->buyer_nick!=$this->usernick){
						$reda["status"]=false;
						$reda["score"]="0";
						$reda["giftname"]="亲，不是您的订单号哦！";
						return $reda;
					}
					
					if((float)$resp->trade->payment<$shopcfg["order_payment"]){
						$reda["status"]=false;
						$reda["score"]=0;
						$reda["giftname"]="抱歉，".$shopcfg["order_payment"]."元以上的订单才可以抽奖。";
						if($shopcfg["andor"]!=1){
							return $reda;
						}
					}else{
						$trade_rule[] = "payment";
					}
					
					if($shopcfg["order_items"]){
						$orderitems = explode(",",$shopcfg["order_items"]);
						$hasitem = false;
						foreach($resp->trade->orders->order as $order){
							foreach($orderitems as $item){
								if($order->num_iid == $item){
									$hasitem=true;
								}
							} 
						}
						if(!$hasitem){
							$reda["status"]=false;
							$reda["score"]="0";
							$reda["giftname"]="亲，只有购买指定商品才可以抽奖哦！请仔细查看抽奖规则。";
							if($shopcfg["andor"]!=1){
								return $reda;
							}
						}else{
							$trade_rule[] = "hasitem";
						}
					}
					if($shopcfg["order_pay_time_start"]||$shopcfg["order_pay_time_end"]){
						if($resp->trade->pay_time){
							if(strtotime($resp->trade->pay_time)<strtotime($shopcfg["order_pay_time_start"])){
								$reda["status"]=false;
								$reda["score"]="0";
								$reda["giftname"]="亲，只有".$shopcfg["order_pay_time_start"]."之后的订单才可以抽奖哦！";
								if($shopcfg["andor"]!=1){
									return $reda;
								}
							}else{
								$after_start = true;
							}
							if(strtotime($resp->trade->pay_time)>strtotime($shopcfg["order_pay_time_end"])){
								$reda["status"]=false;
								$reda["score"]="0";
								$reda["giftname"]="亲，只有".$shopcfg["order_pay_time_end"]."之前的订单才可以抽奖哦！";
								if($shopcfg["andor"]!=1){
									return $reda;
								}
							}else{
								$befor_end = true;
							}
							if($after_start&&$befor_end){
								$trade_rule[] = "intime";
							}
						}
						if(count($trade_rule)==0&&$shopcfg["andor"]==1){
							$reda["status"]=false;
							$reda["score"]="0";
							$reda["giftname"]="亲，您的订单不满足抽奖条件哦！只有购买了指定商品，或"
											  .$shopcfg["order_pay_time_start"]."-".$shopcfg["order_pay_time_end"]."之间的订单，"
											  ."或".$shopcfg["order_payment"]."元以上的订单才可以抽奖哦！";
							return $reda;
						}
						// else{
							// $reda["status"]=false;
							// $reda["score"]="0";
							// $reda["giftname"]="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
							// return $reda;
						// }
					}
					unset($reda);
					if($topic["status"]<4&&$topic["topic"]==(string)$resp->trade->status){
						$reda["status"]=false;
						$reda["score"]=0;
						switch ((string)$resp->trade->status){
							case "WAIT_BUYER_PAY" :
							$reda["giftname"].="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
							break;
							case "TRADE_CLOSED" :
							$reda["giftname"].="亲，订单已被关闭哦！不能使用这个订单号，请再拍一件商品吧！";
							break;
							case "TRADE_CLOSED_BY_TAOBAO" :
							$reda["giftname"].="亲，订单已被关闭哦！不能使用这个订单号，请再拍一件商品吧！";
							break;
							case "TRADE_NO_CREATE_PAY" :
							$reda["giftname"].="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
							break;
							case "PAY_PENDING" :
							$reda["giftname"].="亲，国际信用卡支付正在确认，请稍后再来哦！";
							break;
							case "WAIT_PRE_AUTH_CONFIRM" :
							$reda["giftname"].="亲，0元购合约订单进行中，请交易成功后再来抽奖哦！或者输入其他订单号试试吧！";
							break;
							case "WAIT_BUYER_CONFIRM_GOODS" :
							$reda["giftname"].="亲，我们正在等您确认收货哦！请您确认收货并好评后再来抽奖！";
							break;
							case "WAIT_SELLER_SEND_GOODS" :
							$reda["giftname"].="亲，我们正在为您发货！请您收到货并好评后再来抽奖！";
							break;
							case "SELLER_CONSIGNED_PART" :
							$reda["giftname"].="亲，我们正在为您发货！请您收到货并好评后再来抽奖！";
							break;
							case "TRADE_BUYER_SIGNED" :
							$reda["giftname"].="亲，您已经签收快递，请等待我们收到款以后您就可以抽奖啦！";
							break;
							// case "TRADE_FINISHED" :
							// $reda["giftname"].="亲，交易已成功，请多多购买哦！买的多，抽的多！";
							// break;
						}
						// if(!$resp->trade->buyer_rate&&(string)$resp->trade->status=="TRADE_FINISHED"){
							// $reda["giftname"]="这个订单正在等待您的评价哦！";
						// }
						if($reda["giftname"]){
							$reda["giftname"]="订单状态没有变化哦！<br />".$reda["giftname"];
							return $reda;
						}
					}
					
					unset($reda);
					switch ((string)$resp->trade->status){
						case "WAIT_BUYER_PAY" :
						$reda["giftname"]="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
						break;
						case "TRADE_CLOSED" :
						$reda["giftname"]="亲，订单已被关闭哦！不能使用这个订单号，请再拍一件商品吧！";
						break;
						case "TRADE_CLOSED_BY_TAOBAO" :
						$reda["giftname"]="亲，订单已被关闭哦！不能使用这个订单号，请再拍一件商品吧！";
						break;
						case "TRADE_NO_CREATE_PAY" :
						$reda["giftname"]="亲，您还没付款哦！请赶紧付款，马上就可以抽奖啦！";
						break;
						case "PAY_PENDING" :
						$reda["giftname"]="亲，国际信用卡支付正在确认，请稍后再来哦！";
						break;
						case "WAIT_PRE_AUTH_CONFIRM" :
						$reda["giftname"]="亲，0元购合约订单进行中，请交易成功后再来抽奖哦！或者输入其他订单号试试吧！";
						break;
						case "TRADE_BUYER_SIGNED" :
						$reda["giftname"].="亲，您已经签收快递，请等待我们收到款以后您就可以抽奖啦！";
						break;
						// case "WAIT_BUYER_CONFIRM_GOODS" :
						// $reda["giftname"]="亲，正在等您确认收货哦！请您确认收货后再来抽奖！";
						// break;
					}
					if($reda["giftname"]){
						$reda["status"]=false;
						$reda["score"]=0;
						return $reda;
					}
					
					// 付款后抽奖
					if(((string)$resp->trade->status == "WAIT_SELLER_SEND_GOODS"||(string)$resp->trade->status == "SELLER_CONSIGNED_PART"||(string)$resp->trade->status == "WAIT_BUYER_CONFIRM_GOODS")&&$topic["status"]<2){
						$score_add += ($bei>0)?($shopcfg["order_pay_times"]*$bei):$shopcfg["order_pay_times"];
						$status = 2;
					}
					// 收货后抽奖，要加上付款后抽奖次数
					if((string)$resp->trade->status == "TRADE_FINISHED"&&$topic["status"]<3){
						if(!$save||$topic["status"]<2){
							// 未保存时，为用户直接在完成时抽奖，视为从未抽奖，则应加上付款时的机会
							// 已保存，应判断是否为付款时抽过奖，如从未抽过则应增加机会，抽过则不给机会
							$score_add += ($bei>0)?($shopcfg["order_pay_times"]*$bei):$shopcfg["order_pay_times"];
						}
						$score_add += ($bei>0)?($shopcfg["order_success_times"]*$bei):$shopcfg["order_success_times"];
						$status = 3;
					}
					// 评价后抽奖，要加上前两次
					$rate_level = 0;
					if($this->readoid&&!$resp->trade->buyer_rate&&$shopcfg["tms_goodrate"]>0){
						$tmshp = ($bei>0)?($shopcfg["tms_goodrate"]*$bei):$shopcfg["tms_goodrate"];
						$reda["status"]=false;
						$reda["score"]="0";
						$reda["giftname"]="1亲，您没有好评哦！不能获得".$tmshp."次好评抽奖机会！请给出好评就可以再抽".$tmshp."次啦！";
						return $reda;
					}
					if((string)$resp->trade->buyer_rate=="true"){
						if($shopcfg["tms_goodrate"]>0&&($topic["status"]<4||$status<4)){
							Vendor('taobaosdk.top.request.TraderatesGetRequest');
							$req = new \TraderatesGetRequest;
							$req->setFields("result,content");
							$req->setRateType("give");
							$req->setRole("seller");
							$req->setPageNo(1);
							$req->setPageSize(100);
							$req->setTid($this->oid);
							$rate = $this->c->execute($req, $shopcfg["sessionkey"]);
							if($rate->code){
								$reda["status"]=false;
								$reda["score"]="0";
								if($rate->sub_msg){
									$reda["giftname"]="错误！".$rate->sub_msg;
								}else{
									$reda["giftname"]="错误！请输入正确的订单号！";
								}
								return $reda;
							}
							
							$badwd = false;
							$content = "";
							$rate_level="";
							foreach($rate->trade_rates->trade_rate as $traderate){
								$rate_level = (string)$traderate->result;
								if($rate_level=="bad"||$rate_level=="neutral"){
									break;
								}
								$content.=(string)$traderate->content;
							}
							
							if($this->readoid&&$rate_level!="good"||$rate->total_results==0){
								$tmshp = ($bei>0)?($shopcfg["tms_goodrate"]*$bei):$shopcfg["tms_goodrate"];
								$reda["status"]=false;
								$reda["score"]="0";
								$reda["giftname"]="亲，您没有好评哦！不能获得".$tmshp."次好评抽奖机会！请给出好评就可以再抽".$tmshp."次啦！注意：追加的不算。";
								return $reda;
							}
							
							if($rate_level=="good"){
								$kwds = explode(",",$shopcfg["goodrate_kwd"]);
								foreach($kwds as $kwd){
									if(strpos($content,$kwd)){
										$badwd=true;
									}
								}
							}
							if($badwd){
								$reda["status"]=false;
								$reda["score"]="0";
								$reda["giftname"]="亲，您给出的评价内容我们无法接受，抱歉您不能抽奖！";
								return $reda;
							}
							if($topic["status"]<4&&$rate_level=="good"&&!$badwd){
								if($topic["status"]<2&&$status<2){
								$score_add += ($bei>0)?($shopcfg["order_pay_times"]*$bei):$shopcfg["order_pay_times"];
								}
								if($topic["status"]<3&&$status<3){
								$score_add += ($bei>0)?($shopcfg["order_success_times"]*$bei):$shopcfg["order_success_times"];
								}
								$score_add += ($bei>0)?($shopcfg["tms_goodrate"]*$bei):$shopcfg["tms_goodrate"];
								$status = 4;
							}
						}
					}
					switch((string)$resp->trade->status){
						case "WAIT_SELLER_SEND_GOODS":$trade_type=1;break;
						case "TRADE_FINISHED":$trade_type=9;break;
						case "WAIT_BUYER_PAY":$trade_type=0;break;
						default:$trade_type=10;break;
					}
					// 存储订单号，不再判断订单类型
					// if((string)$resp->trade->status == "WAIT_SELLER_SEND_GOODS"||(string)$resp->trade->status == "TRADE_FINISHED"||(string)$resp->trade->status == "SELLER_CONSIGNED_PART"){
					if(!$save){
						$data["sid"]=$this->sid;
						$data["user_id"]=$shopcfg["taobao_user_id"];
						$data["user_nick"]=$shopcfg["usernick"];
						$data["buyer_nick"]=(string)$resp->trade->buyer_nick;
						$data["payment"]=(float)$resp->trade->payment;
						$data["oid"]=$this->oid;
						$data["tid"]=$this->oid;
						$data["type"]='';
						$data["pub_time"]=$resp->trade->pay_time?date("Y-m-d H:i:s",strtotime($resp->trade->pay_time)):date("Y-m-d H:i:s");
						$data["topic"]=(string)$resp->trade->status;
						$data["trade_type"]=$trade_type;
						$data["rate_level"]=$rate_level;
						$data["ts"]=date("Y-m-d H:i:s");
						$data["status"]=$status;
						$Order->add($data);
					}else{
						$data["status"]=$status;
						$data["topic"]=(string)$resp->trade->status;
						$data["trade_type"]=$trade_type;
						$data["rate_level"]=$rate_level;
						$Order->where("`oid`=".$this->oid)->save($data);
					}
					unset($data);
					// }
					// $order = "INSERT INTO `sm_orders` (`sid`,`user_id`, `user_nick`, `buyer_nick`, `payment`, `oid`, `tid`, `type`, `pub_time`, `topic`, `trade_type`,`rate_level`,`ts`) VALUES ";
					// $order .= "('$this->sid','0', '0', '$resp->trade->buyer_nick', '$resp->trade->payment', '$this->oid', '$this->oid', '', '2000-01-01 00:00:00', '$resp->trade->status','$trade_type','$rate_level','".date("Y-m-d H:i:s")."',2 )";
					// $Order->execute($order);
				}else{
					$reda["status"]=false;
					$reda["score"]=0;
					$reda["giftname"]="抱歉，没找到该订单。亲，3个月以内的订单号才可以哦！";
					return $reda;
				}

			}
		}
		$U = D("EventsUsers");
		$Uscore = current($U->where("`uzuid`='".$this->UserSPID."' AND `sid`=".$this->sid." AND `eventid`=".$this->eid)->limit(1)->getField("id,id,score,likeme,shareme,collect,followme,refond,addtime"));//echo $U->_sql();
		
		if($shopcfg["tms_everyday"]>0){
			if(date("Ymd",strtotime($Uscore["addtime"]))!=date("Ymd")){
				$score_add += $shopcfg["tms_everyday"];
			}
		}
		if(!$Uscore){
			$data["score"] = $shopcfg["tms_newcomer"]+$score_add;
			$data["uzuid"] = $this->UserSPID;
			$data["sid"] = $this->sid;
			$data["addtime"]=date("Y-m-d H:i:s",time());
			$data["likeme"]=0;
			$data["shareme"]=0;
			$data["collect"]=0;
			$data["followme"]=0;
			$Uscore = $data;
			$score = $data["score"];
			$this->scoreid = $U->add($data);
		}else{
			$score = $Uscore["score"];
			if($score_add>0){
				$score+=$score_add;
				$data["addtime"]=date("Y-m-d H:i:s",time());
				$data["score"]=$score;
				$U->where("`id`=".$Uscore["id"])->save($data);//echo $U->_sql();
				// $U->where("`id`=".$Uscore["id"])->setField('`score`','`score`+'.$score_add);
				// $U->where("`id`=".$Uscore["id"])->setInc('score',$score_add);
			}
			$this->scoreid = $Uscore["id"];
		}
		// echo $score_add;
		// return;
		$status=false;
		if($shopcfg["likeme"]==1||$shopcfg["shareme"]==1||$shopcfg["collect"]==1||$shopcfg["followme"]==1||$shopcfg["brandid"]!=0){
			if($Uscore["likeme"]!=$shopcfg["likeme"]){
				$status = true;
				$gname[] = "喜欢本店铺才可抽奖！请点击喜欢！";
				$mission[] = "like";
			}
			if($Uscore["shareme"]!=$shopcfg["shareme"]){
				$status = true;
				$gname[] = "分享本活动才可抽奖，请分享！";
				$mission[] = "sharebtn";
			}
			if($Uscore["collect"]!=$shopcfg["collect"]){
				$status = true;
				$gname[] = "收藏卖家店铺才可抽奖，请收藏！";
				$mission[] = "followshop";
			}
			if($Uscore["followme"]!=$shopcfg["followme"]){
				$status = true;
				$gname[] = "关注卖家才可抽奖，请关注！";
				$mission[] = "friendfollow";
			}
			if($shopcfg["brandid"]>0&&$Uscore["refond"]!=1){
				$status = true;
				$gname[] = "关注品牌才可抽奖，请关注！";
				$mission[] = "brandid";
			}
		}
		if($status){
			$reda["status"]="mission";
			$reda["score"]=0;
			$reda["giftname"]="请完成以下任务再抽奖：";	
			$reda["mission"]=implode(",",$mission);	
			return $reda;
		}
			$G = M("EventsGifts");
			$this->gifts = $G->cache(true)->where("`sid`=".(int)$this->sid." AND `status`=0")->getField("id,name,probability,isshow,quantity,pic_url,type,level,price,num_iids,tagid");
			
			if($score>0){
				$re = $this->ShopLotter();
				if($re>0){$reda["status"]=true;}else{$reda["status"]=false;}
				$reda["giftname"]=$this->gifts[$re]["name"];	
				$reda["giftpic"]=$this->gifts[$re]["pic_url"];	
				$reda["type"]=$this->gifts[$re]["type"];	
				$reda["level"]=$this->gifts[$re]["level"];	
				if($this->gifts[$re]["type"]==4){
					$reda["cardno"]=$this->gifts[$re]["cardno"];
					$reda["secret"]=$this->gifts[$re]["secret"];
				}else{
					$reda["withdraw"]=$this->gifts[$re]["num_iids"];	
				}
				$reda["gid"]=$re;	
				$reda["ugid"]=$this->ugid;	
				$reda["score"].='您还有'.--$score.'次机会！';				
			}else{
				$reda["status"]=false;
				$reda["giftname"]="您的抽奖机会已经用完啦！";	
				if($shopcfg["tms_everyday"]>0){
					$reda["giftname"].="明天再来还可以抽".$shopcfg["tms_everyday"]."次哦！";
				}
				if($shopcfg["orderset"]==1){
					$reda["giftname"].="订单不同阶段有不同的抽奖机会，亲们多输入几次试试哦！";
				}
				
			}
			$reda["score"]=$score;
			return $reda;
	}
	public function ShopLotter(){
		foreach($this->gifts as $k=>$gift){ //中奖率分布
			if($gift["quantity"]>0){
				$LotArr[$k]=$gift["probability"];
			}else{
				$nonequantity += $gift["probability"];
				//数量为0的奖品概率要增加到不中奖
			}
		}
		if(array_sum($LotArr)<10000){
			$none = array(
				"name"=>"再接再厉，大奖不远啦！",
				"probability"=>10000-array_sum($LotArr)+$nonequantity,
				"quantity"=>0,
				"type"=>0,
			);
			$this->gifts[0]=$none;
			$LotArr[0]=10000-array_sum($LotArr)+$nonequantity;
		}
		// 中奖率分布结束，抽取
		$re = $this->Lottery($LotArr);
		$UG = D("UsersGifts");
		if($re<>0){
			if($this->gifts[$re]["type"]==7){
				// 中得再来一次增加次数
				$score_ingift = (int)$this->gifts[$re]["num_iids"];
				$UG->execute("update `sm_events_users` set `score` = `score`+".$score_ingift." WHERE `id` = ".$this->scoreid);
			}
			if($this->gifts[$re]["type"]==5){
				// 中得折扣类型奖品，远程加载贴标签动作
				$tagid = $this->gifts[$re]["tagid"];
				$ts = time();
				$sign=md5(C('TOOL_KEY').$ts.($this->usernick).$tagid.$this->sid.$action.C('TOOL_SECRET')); 
				$r = $fetchService->fetchByGet("http://hg.itianshan.com/?m=Shopmodule&a=adduser&shopid=".$this->sid."&usernick=".urlencode_utf8($this->usernick)."&tagid=".$tagid."&ts=".$ts."&sign=".$sign);
			}
			//读取用户奖品列表是否已经有该奖品
			$this->ugid = $UG->where("`giftid`=".$re." AND `uzuid`=".$this->UserSPID)->getField("`id`");
			if($this->ugid&&$this->gifts[$re]["type"]!=7&&$this->gifts[$re]["type"]!=4){
				// 如果有该奖品，除再来一次和卡密外，都更新奖品数量
				$UG->where("`id`=".$this->ugid)->setInc('quantity');
			}
			if(!$this->ugid||$this->gifts[$re]["type"]==7||$this->gifts[$re]["type"]==4){
				// 7：再来一次 4：卡密，均可以重复中出
				// 再来一次、卡密不增加次数，每次中出都增加记录，默认数量为1
				if($this->gifts[$re]["type"]==4){
					// 中得卡密要保存卡密id
					$KM = M("EventsGiftsKm");
					$kami = current($KM->where("`giftid`=".$re." AND `sid`=".$this->sid." AND `status`=8")->getField("`id`,`id`,`cardno`,`secret`"));
					if($kami){
						$data["kamiid"]=$kami["id"];
						$this->gifts[$re]["cardno"]=$kami["cardno"];
						$this->gifts[$re]["secret"]=$kami["secret"];
						$kmsv["status"]=9;
						$kmsv["shopuid"]=$this->UserSPID;
						$KM->where("`id`=".$kami["id"])->save($kmsv);
					}else{
						$this->gifts[$re]["cardno"]="没有卡号";
						$this->gifts[$re]["secret"]="";
					}
				}
				$data["giftid"]=$re;
				$data["uzuid"]=$this->UserSPID;
				$data["sid"]=$this->sid;
				$data["gtype"]=$this->gifts[$re]["type"];
				$data["actiontime"]=date("Y-m-d H:i:s",time());
				$tp=Array(2,3,4,5,6,7);//除实物外的奖品设置为已发奖状态
				if(in_array($this->gifts[$re]["type"],$tp)){
					$data["status"]=1;
				}
				$this->ugid = $UG->add($data); //为用户增加一个中奖记录
				$UG->execute("update `sm_events_gifts` set `quantity` = IF(`quantity`<1, 0, `quantity`-1) WHERE `id` = ".$re);
			}
			if($this->gifts[$re]["type"]!=7){
			$wins = ", `wins` = `wins`+1 ";//echo $scoreid.$U->_sql();
			}
			// foreach(C("GFT_TYPE") as $tp){
				// if($this->gifts[$re]["type"]==2){
					// $status = ",`sum_youhuiq_send`=`sum_youhuiq_send`+1,`sum_youhuiq_send_value`=`sum_youhuiq_send_value`+".$this->gifts[$re]["price"];
				// }elseif($this->gifts[$re]["type"]==3){
					// $status = ",`sum_baoyou_send`=`sum_baoyou_send`+1,`sum_baoyou_send_value`=`sum_baoyou_send_value`+".$this->gifts[$re]["price"];
				// }elseif($this->gifts[$re]["type"]==4){
					// $status = ",`sum_zfbhb_send`=`sum_zfbhb_send`+1,`sum_zfbhb_send_value`=`sum_zfbhb_send_value`+".$this->gifts[$re]["price"];
				// }elseif($this->gifts[$re]["type"]==5){
					// $status = ",`sum_zhekou_send`=`sum_zhekou_send`+1,`sum_zhekou_send_value`=`sum_zhekou_send_value`+".$this->gifts[$re]["price"];
				// }
			// }
		}
		$UG->execute("update `sm_events_users` set `score` = IF(`score`<1, 0, `score`-1) WHERE `id` = ".$this->scoreid);//echo $scoreid.$U->_sql();
		$UG->execute("update `sm_shop_cfg` set `lotts` = `lotts`+1".$wins." WHERE `sid` = ".$this->sid);//echo $scoreid.$U->_sql();
		$UG->execute("update `sm_user` set `lotts` = `lotts`+1".$wins." WHERE `id` = ".$this->UserUZID);//echo $scoreid.$U->_sql();
		$UG->execute("update `sm_shop_users` set `lotts` = `lotts`+1".$wins." WHERE `id` = ".$this->UserSPID." AND `sid`=".$this->sid);//echo $scoreid.$U->_sql();
		// $UG->execute("update `uz_status` set `lotts` = `lotts`+1".$wins.$status);
		return $re;
	}
	
	public function DoLott(){
			$E = M("Events");
			$content = current($E->where("`id`=".$this->eid)
						 ->getField("
						`id`,
						`start_time`,
						`end_time`,
						`status`,
						`tms_newcomer`,
						`tms_paid`,
						`tms_finish`,
						`tms_sumpay`,
						`tms_rated`,
						`tms_collect`,
						`sumpay`,
						`goodrate`,
						`refond`,
						`likeme`,
						`followme`,
						`fanscont`,
						`shareme`,
						`collect`,
						`weitao`,
						`weibo_fl`,
						`weibo_fs`,
						`weibo_fx`,
						`newcomer`,
						`oldcomer`,
						`trade_times`,
						`buyer_vip`,
						`buyer_lev`,
						`buyer_signday`,
						`location`"
						));
			if(strtotime($content["end_time"])-time()<0){
				$reda["status"]=false;
				$reda["giftname"]="活动已经结束！";	
				return $reda;
			}
			if(strtotime($content["start_time"])-time()>0){
				$reda["status"]=false;
				$reda["giftname"]="活动尚未开始！";	
				return $reda;
			}
			$U = D("EventsUsers");
			$Uscore = current($U->cache(true)->where("`uzuid`='".$this->UserUZID."' AND `eventid`=".$this->eid)->limit(1)->getField("id,id,score,likeme,shareme,collect,followme"));//echo $U->_sql();
			if(!$Uscore){
				$data["score"] = $content["tms_newcomer"];
				$data["uzuid"] = $this->UserUZID;
				$data["eventid"]=$this->eid;
				$data["addtime"]=date("Y-m-d H:i:s",time());
				$data["likeme"]=0;
				$data["shareme"]=0;
				$data["collect"]=0;
				$data["followme"]=0;
				$Uscore = $data;
				$score = $data["score"];
				$this->scoreid = $U->add($data);
			}else{
				$score = $Uscore["score"];
				$this->scoreid = $Uscore["id"];
			}
			if($content["likeme"]==1||$content["shareme"]==1||$content["collect"]==1||$content["followme"]==1){
				$status=true;
				if($Uscore["likeme"]!=$content["likeme"]){
					$status = false;
					$gname[] = "喜欢本店铺才可抽奖！请点击喜欢！";
					$mission[] = "like";
				}
				if($Uscore["shareme"]!=$content["shareme"]){
					$status = false;
					$gname[] = "分享本活动才可抽奖，请分享！";
					$mission[] = "sharebtn";
				}
				if($Uscore["collect"]!=$content["collect"]){
					$status = false;
					$gname[] = "收藏卖家店铺才可抽奖，请收藏！";
					$mission[] = "followshop";
				}
				if($Uscore["followme"]!=$content["followme"]){
					$status = false;
					$gname[] = "关注卖家才可抽奖，请关注！";
					$mission[] = "friendfollow";
				}
			}
			if(!$status){
				$reda["status"]="mission";
				$reda["giftname"]="请完成以下任务再抽奖：<br />".implode("<br />",$gname);	
				$reda["mission"]=implode(",",$mission);	
				return $reda;
			}
			$G = D("EventsGifts");
			$this->gifts = $G->cache(true)->where("`event_id`=".(int)$this->eid)->getField("id,name,probability,isshow,quantity,pic_url,type,price,num_iids");
			
			if($score>0){
				$re = $this->EventLotter();
				if($re>0){$reda["status"]=true;}else{$reda["status"]=false;}
				$reda["giftname"]=$this->gifts[$re]["name"];	
				$reda["giftpic"]=$this->gifts[$re]["pic_url"];	
				$reda["type"]=$this->gifts[$re]["type"];	
				$reda["withdraw"]=$this->gifts[$re]["num_iids"];	
				$reda["gid"]=$re;	
				$reda["ugid"]=$this->ugid;	
				$reda["score"].='您还有'.--$score.'次机会！';				
			}else{
				$reda["status"]=false;
				$reda["giftname"]="您的抽奖机会已经用完啦！订单不同阶段有不同的抽奖机会，亲们多输入几次试试哦！";	
			}
			return $reda;
	}
	// 必要参数：
	// $L->UserUZID = $this->UserUZID; 本站用户id
	// $L->eid = $this->eid; 活动id
	// $L->scoreid = $this->scoreid;  参与活动用户计数id
	// $L->gifts = $this->gifts; 奖品列表
	public function EventLotter(){
		foreach($this->gifts as $k=>$gift){
			if($gift["quantity"]>0){
				$LotArr[$k]=$gift["probability"];
			}else{
				$nonequantity += $gift["probability"];
				//数量为0的奖品概率要增加到不中奖
			}
		}
		if(array_sum($LotArr)<10000){
			$none = array(
				"name"=>"再接再厉，大奖不远啦！",
				"probability"=>10000-array_sum($LotArr)+$nonequantity,
				"quantity"=>0,
				"type"=>0,
			);
			$this->gifts[0]=$none;
			$LotArr[0]=10000-array_sum($LotArr)+$nonequantity;
		}
		$re = $this->Lottery($LotArr);
		$UG = D("UsersGifts");
		if($re<>0){
			$this->ugid = $UG->where("`giftid`=".$re." AND `uzuid`=".$this->UserUZID)->getField("`id`");
			if(!$this->ugid){
			$data["uzuid"]=$this->UserUZID;
			$data["giftid"]=$re;
			$data["eventid"]=$this->eid;
			$data["actiontime"]=date("Y-m-d H:i:s",time());
			if($this->gifts[$re]["type"]==2||$this->gifts[$re]["type"]==3||$this->gifts[$re]["type"]==4||$this->gifts[$re]["type"]==5){
				$data["status"]=1;
			}
			$this->ugid = $UG->add($data);
			$UG->execute("update `uz_events_gifts` set `quantity` = IF(`quantity`<1, 0, `quantity`-1) WHERE `id` = ".$re);
			}
			$wins = ", `wins` = `wins`+1 ";//echo $scoreid.$U->_sql();
			foreach(C("GFT_TYPE") as $tp){
				if($this->gifts[$re]["type"]==2){
					$status = ",`sum_youhuiq_send`=`sum_youhuiq_send`+1,`sum_youhuiq_send_value`=`sum_youhuiq_send_value`+".$this->gifts[$re]["price"];
				}elseif($this->gifts[$re]["type"]==3){
					$status = ",`sum_baoyou_send`=`sum_baoyou_send`+1,`sum_baoyou_send_value`=`sum_baoyou_send_value`+".$this->gifts[$re]["price"];
				}elseif($this->gifts[$re]["type"]==4){
					$status = ",`sum_zfbhb_send`=`sum_zfbhb_send`+1,`sum_zfbhb_send_value`=`sum_zfbhb_send_value`+".$this->gifts[$re]["price"];
				}elseif($this->gifts[$re]["type"]==5){
					$status = ",`sum_zhekou_send`=`sum_zhekou_send`+1,`sum_zhekou_send_value`=`sum_zhekou_send_value`+".$this->gifts[$re]["price"];
				}
			}
		}
		$UG->execute("update `uz_events_users` set `score` = IF(`score`<1, 0, `score`-1) WHERE `id` = ".$this->scoreid);//echo $scoreid.$U->_sql();
		$UG->execute("update `uz_events` set `lotts` = `lotts`+1".$wins." WHERE `id` = ".$this->eid);//echo $scoreid.$U->_sql();
		$UG->execute("update `uz_user` set `lotts` = `lotts`+1".$wins." WHERE `id` = ".$this->UserUZID);//echo $scoreid.$U->_sql();
		$UG->execute("update `uz_status` set `lotts` = `lotts`+1".$wins.$status);
		return $re;
	}
	public function Lottery($proArr){

	/*
	 * 经典的概率算法，
	 * $proArr是一个预先设置的数组，
	 * 假设数组为：array(100,200,300，400)，
	 * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内， 
	 * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间，
	 * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。
	 * 这样 筛选到最终，总会有一个数满足要求。
	 * 就相当于去一个箱子里摸东西，
	 * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。
	 * 这个算法简单，而且效率非常 高，
	 * 关键是这个算法已在我们以前的项目中有应用，尤其是大数据量的项目中效率非常棒。
	 */

    $result = '';  
    //概率数组的总概率精度 
    $proSum = array_sum($proArr);  
    //概率数组循环 
    foreach ($proArr as $key => $proCur) { 
        $randNum = mt_rand(1, $proSum); 
        if ($randNum <= $proCur) { 
            $result = $key; 
            break; 
        } else { 
            $proSum -= $proCur; 
        } 		
    } 
    unset ($proArr);  
    return $result; 
	}
	public function helper(){
	/*
	 * 奖项数组
	 * 是一个二维数组，记录了所有本次抽奖的奖项信息，
	 * 其中id表示中奖等级，prize表示奖品，v表示中奖概率。
	 * 注意其中的v必须为整数，你可以将对应的 奖项的v设置成0，即意味着该奖项抽中的几率是0，
	 * 数组中v的总和（基数），基数越大越能体现概率的准确性。
	 * 本例中v的总和为100，那么平板电脑对应的 中奖概率就是1%，
	 * 如果v的总和是10000，那中奖概率就是万分之一了。
	 * 
	 */
	$prize_arr = array( 
		'0' => array('id'=>1,'prize'=>'平板电脑','v'=>1), 
		'1' => array('id'=>2,'prize'=>'数码相机','v'=>5), 
		'2' => array('id'=>3,'prize'=>'音箱设备','v'=>10), 
		'3' => array('id'=>4,'prize'=>'4G优盘','v'=>12), 
		'4' => array('id'=>5,'prize'=>'10Q币','v'=>22), 
		'5' => array('id'=>6,'prize'=>'下次没准就能中哦','v'=>50), 
	); 

	/*
	 * 每次前端页面的请求，PHP循环奖项设置数组，
	 * 通过概率计算函数get_rand获取抽中的奖项id。
	 * 将中奖奖品保存在数组$res['yes']中，
	 * 而剩下的未中奖的信息保存在$res['no']中，
	 * 最后输出json个数数据给前端页面。
	 */
	foreach ($prize_arr as $key => $val) { 
		$arr[$val['id']] = $val['v']; 
	} 
	$rid = $this->Lottery($arr); //根据概率获取奖项id 

	$res['yes'] = $prize_arr[$rid-1]['prize']; //中奖项 
	unset($prize_arr[$rid-1]); //将中奖项从数组中剔除，剩下未中奖项 
	shuffle($prize_arr); //打乱数组顺序 
	for($i=0;$i<count($prize_arr);$i++){ 
		$pr[] = $prize_arr[$i]['prize']; 
	} 
	$res['no'] = $pr; 
	print_r($res); 
	}
}